package com.wangxin.study8.threadtest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author jojo.wang
 * @title: SemaphoreTestA
 * @projectName study8
 * @description: TODO
 * @date 2019/5/716:10
 */

public class SemaphoreTestA {
    private static final int count = 50;
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(300);
        final Semaphore semaphore = new Semaphore(20);
        for (int i = 0; i < count; i++) {
            final int num = i;
            try {
                SemaphoreWorker semaphoreWorker = new SemaphoreWorker(semaphore);
                executorService.submit(semaphoreWorker);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        executorService.shutdown();
        System.out.println("finish");
    }

}
class SemaphoreWorker implements Runnable{
    private Semaphore semaphore;
    public SemaphoreWorker (Semaphore semaphore){
        this.semaphore = semaphore;
    }
    @Override
    public void run() {
        try {
            log("is waiting for a permit!");
            semaphore.acquire();
            log("acquire a permit!!");
            log("executed!!");
            Thread.sleep(1000L);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            log("release!");
            semaphore.release();
        }
    }
    private void log(String msg){
        String name = "";
        if (null==msg){
            name = Thread.currentThread().getName();
        }
        System.out.println(name+"--"+msg);
    }
}
